package com.bsy.framework.helper

import android.annotation.SuppressLint
import android.os.Build
import java.nio.charset.StandardCharsets
import java.security.Key
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec


/**
 * Created by Sincerity on 2024/3/7.
 * Copyright
 * 描述：
 */
object AESHelper {
    private const val AES_ALGORITHM = "AES"
    private const val AES_TRANSFORMATION = "AES/ECB/PKCS5Padding"

    // 分块加密
    fun encrypt(data: String, key: String): String? {
        return try {
            val cipher = Cipher.getInstance(AES_TRANSFORMATION)
            val secretKey = generateKey(key)
            cipher.init(Cipher.ENCRYPT_MODE, secretKey)
            val plaintextBytes = data.toByteArray(charset("UTF-8"))
            // 计算加密后的数据长度
            val encryptedLength = cipher.getOutputSize(plaintextBytes.size)

            // 创建一个缓冲区来存储加密后的数据
            val encryptedTextBytes = ByteArray(encryptedLength)

            // 分段加密数据
            var encryptedOffset = 0
            var bytesProcessed: Int
            var i = 0
            while (i < plaintextBytes.size) {
                bytesProcessed =
                    cipher.update(plaintextBytes, i, cipher.blockSize.coerceAtMost(plaintextBytes.size - i), encryptedTextBytes, encryptedOffset)
                encryptedOffset += bytesProcessed
                i += cipher.blockSize
            }
            cipher.doFinal(encryptedTextBytes, encryptedOffset)

            // 将加密后的数据转换为Base64编码
            var encryptedText: String? = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                encryptedText = java.util.Base64.getEncoder().encodeToString(encryptedTextBytes)
            }
            encryptedText
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 分块解密
    @SuppressLint("GetInstance")
    fun decrypt(encryptedData: String?, key: String): String? {
        return try {
            val cipher = Cipher.getInstance(AES_TRANSFORMATION)
            val secretKey = generateKey(key)
            cipher.init(Cipher.DECRYPT_MODE, secretKey)

            // 解码Base64编码的字符串，获取加密后的字节数组
            var encryptedTextBytes = ByteArray(0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                encryptedTextBytes = java.util.Base64.getDecoder().decode(encryptedData)
            }
            // 初始化AES Cipher对象，使用ECB模式和PKCS5Padding填充方式
            cipher.init(Cipher.DECRYPT_MODE, secretKey)

            // 计算解密后的数据长度
            val decryptedLength = cipher.getOutputSize(encryptedTextBytes.size)

            // 创建一个缓冲区来存储解密后的数据
            val decryptedTextBytes = ByteArray(decryptedLength)

            // 分段解密数据
            var decryptedOffset = 0
            var bytesProcessed: Int
            var i = 0
            while (i < encryptedTextBytes.size) {
                bytesProcessed = cipher.update(
                    encryptedTextBytes,
                    i,
                    cipher.blockSize.coerceAtMost(encryptedTextBytes.size - i),
                    decryptedTextBytes,
                    decryptedOffset
                )
                decryptedOffset += bytesProcessed
                i += cipher.blockSize
            }
            bytesProcessed = cipher.doFinal(decryptedTextBytes, decryptedOffset)
            decryptedOffset += bytesProcessed

            // 解密后的明文
            String(decryptedTextBytes, 0, decryptedOffset, charset("UTF-8"))
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    private fun generateKey(key: String): Key {
        val keyBytes = key.toByteArray(StandardCharsets.UTF_8)
        return SecretKeySpec(keyBytes, AES_ALGORITHM)
    }

    private fun concatenateArrays(a: ByteArray, b: ByteArray): ByteArray {
        val result = ByteArray(a.size + b.size)
        System.arraycopy(a, 0, result, 0, a.size)
        System.arraycopy(b, 0, result, a.size, b.size)
        return result
    }
}